<?php

include ("/var/www/html/wxapps.lovemojito.com/mApp/php/wechat.class.php"); //引入微信类

$wechatObj = new Wechat(); //实例化微信类
$conn = connect_to_db();

$wechatObj->setConn($conn);
$token = $wechatObj->getAccessToken();

global $CONFIG;
$appid = $CONFIG['appid'];
$secret = $CONFIG['secret'];
echo $appid;
//刚开始等待时间为1s
$sleepTime = 1;

while (true)
{
    echo "-------------------------------------------------------------------------------------------\n";
    echo date('Y-m-d H:i:s', time()) . "\tnow start\n";
    $token = "unknown";
    //先看库里有的是否过期
    $result = mysql_query("select * from weixin_token where appID='$appid' and expireTime > (now() + interval 10 minute)",
        $conn);
    if (is_resource($result) && mysql_num_rows($result) != 0)
    {
        $row = mysql_fetch_array($result, MYSQL_ASSOC);
        $token = $row['token'];
        $expireTime = $row['expireTime'];
        echo date('Y-m-d H:i:s', time()) . "\tcurrent token: $token  \texpireTime: $expireTime \n";
        $needUpdate = false;
    }else{
        $needUpdate = true;
    }



    //判断token是否有效



    if ($needUpdate)
    {
        $url = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=$appid&secret=$secret";
        $data = enhancedFetchUrlContent("unknown", $url, "获取token", "getToken", $conn, 10, false); //通过自定义函数getCurl得到https的内容
        $resultArr = json_decode($data, true); //转为数组

        if (isset($resultArr["access_token"]))
        {
            $token = $resultArr["access_token"]; //获取access_token
            $expires_in = $resultArr["expires_in"];
            $sql = "insert into weixin_token (appID, secret, token, expireTime, updateTime) ";
            $sql .= "values ('$appid', '$secret', '$token', (now() + interval $expires_in second), now()) ";
            $sql .= " on DUPLICATE KEY UPDATE token='$token', expireTime=(now() + interval $expires_in second), updateTime = now();";
            mysql_query($sql, $conn);
            echo date('Y-m-d H:i:s', time()) . "\tget new token: $token  \texpireTime: $expires_in \n";
            $sleepTime = 20;
        } else
        {
            echo date('Y-m-d H:i:s', time()) . "\t$url get new token failed: " . $resultArr['errmsg'] .
                "\n";
            if ($resultArr['errmsg'] == "api freq out of limit")
            {
                $sleepTime += 10;
            }
        }

    }

    $leftTime = strtotime(date('Y-m-d', strtotime('+1 day'))) - time();
    if ($leftTime < $sleepTime)
    {
        $sleepTime = $leftTime;
    }

    if ($sleepTime > 300)
    {
        $sleepTime = 300;
    }
    echo date('Y-m-d H:i:s', time()) . "\twait $sleepTime seconds, left $leftTime seconds till next day\n";
    echo date('Y-m-d H:i:s', time()) . "\tnow end\n";
    echo "-------------------------------------------------------------------------------------------\n";
    sleep($sleepTime);

}

mysql_close($conn);

?>
